package com.fc.remoting.protocol;


import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fc.remoting.core.HttpProtocolTask;
import com.fc.remoting.core.RemotingThreadPool;
import com.fc.remoting.core.RemotingTask;
import com.fc.remoting.protocol.IProtocol;
import com.fc.remoting.protocol.RemotingHttpProtocol;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

public class ProtocolAdapter {
	private IProtocol handler = null;

	public static ProtocolAdapter valueOf(IProtocol handler) {
		ProtocolAdapter adapter = new ProtocolAdapter();
		adapter.handler = handler;
		return adapter;
	}

	/**
	 * 处理netty过来的Http请求
	 * @param request
	 * @param ctx
	 */
	public void process(JSONObject request, ChannelHandlerContext ctx) {
		RemotingThreadPool.Instance.getInstance().submitTask(new HttpProtocolTask(ctx, handler, request));
	}
	
	/**
	 * 处理servlet过来的Http请求
	 * @param requestBody
	 * @param response
	 */
	public void process(JSONObject requestBody,HttpServletResponse response){
	}
	
	/**
	 * 处理tcp请求
	 * @param request
	 * @param channel
	 */
	public void processTcpRequest(JSONObject request,Channel channel){
		RemotingThreadPool.Instance.getInstance().submitTask(new RemotingTask(channel, handler, request));
	}
	
	/**
	 * 处理servlet过来的Http请求
	 * @param response {@link HttpServletResponse}
	 * @param request {@link JSONObject} Http请求消息体
	 * @return 返回给客户端的消息内容
	 */
	public Object processHttpRequestStraight(HttpServletResponse response,JSONObject request) {
		return ((RemotingHttpProtocol)handler).doHandler(response,request);
	}

	public boolean hasProcessor() {
		return handler != null;
	}

	@Override
	public String toString() {
		return handler.getClass().getName();
	}
}
